﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;

namespace HttpCore
{
    public class HttpCore
    {
        public static ManualResetEvent allDone = new ManualResetEvent(false);
        /// <summary>
        /// 构造方法
        /// </summary>
        public HttpCore()
        {

        }
        /// <summary>
        /// 获取OA当前登录的Cookies
        /// </summary>
        /// <param name="OA_LOGIN_URL">OA的登录地址</param>
        /// <param name="paramData">要传的用户名密码参数</param>
        /// <param name="dataEncode">要用何种编码</param>
        /// <returns></returns>
        public string GetCookie(string OA_LOGIN_URL, string paramData, Encoding dataEncode)
        {
            string Cookiesstr = null;
            CookieCollection cookies = new CookieCollection();
            HttpWebRequest request = null;
            request = (HttpWebRequest)WebRequest.Create(OA_LOGIN_URL);
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(cookies);
            byte[] byteArray = dataEncode.GetBytes(paramData); //转化
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            Stream newStream = request.GetRequestStream();
            newStream.Write(byteArray, 0, byteArray.Length);//写入参数
            newStream.Close();
            //Get the response from the server and save the cookies from the request..
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Cookiesstr = request.CookieContainer.GetCookieHeader(request.RequestUri);
            return Cookiesstr;
        }
        /// <summary>
        /// 登录是否成功
        /// </summary>
        /// <param name="OA_LOGIN_URL"></param>
        /// <param name="paramData"></param>
        /// <param name="dataEncode"></param>
        /// <returns></returns>
        public string OALoginPost(string OA_LOGIN_URL, string paramData, Encoding dataEncode)
        {
            string resultstr = null;
            //实例化一个HttpWebRequest对象并通过抽象工厂去创建。
            HttpWebRequest httpwebrequest = HttpWebRequest.Create(OA_LOGIN_URL) as HttpWebRequest;
            //创建流byte数组来装载参数
            byte[] paramArray = dataEncode.GetBytes(paramData);
            //创建空的Cookie用于初始化Cookie
            //CookieContainer cookiecontainer = new CookieContainer();
            //重置Cookie
            //httpwebrequest.CookieContainer = cookiecontainer;
            //设置当前请求为POST动作
            httpwebrequest.Method = "POST";
            //当前请求的mime头
            httpwebrequest.ContentType = "application/x-www-form-urlencoded";
            //设置参数头长度
            httpwebrequest.ContentLength = paramArray.Length;
            //写入登录后的Cookies
            //httpwebrequest.Headers.Add("Cookie", OACookie);
            //请求开始流
            Stream streamrequest = httpwebrequest.GetRequestStream();
            //写入参数
            streamrequest.Write(paramArray, 0, paramArray.Length);
            streamrequest.Close();

            HttpWebResponse response = (HttpWebResponse)httpwebrequest.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
            resultstr = sr.ReadToEnd();
            sr.Close();

            response.Close();
            streamrequest.Close();
            httpwebrequest.Abort();
            return resultstr;
        }

        public string OASignIn(string OA_LOGIN_URL, string paramData, Encoding dataEncode, string _OACookie)
        {
            string resultstr = null;
            //实例化一个HttpWebRequest对象并通过抽象工厂去创建。
            HttpWebRequest httpwebrequest = HttpWebRequest.Create(OA_LOGIN_URL) as HttpWebRequest;
            //创建流byte数组来装载参数
            byte[] paramArray = dataEncode.GetBytes(paramData);
            //创建空的Cookie用于初始化Cookie
            //CookieContainer cookiecontainer = new CookieContainer();
            //重置Cookie
            //httpwebrequest.CookieContainer = cookiecontainer;
            //设置当前请求为POST动作
            httpwebrequest.Method = "POST";
            //当前请求的mime头
            httpwebrequest.ContentType = "application/x-www-form-urlencoded";
            //设置参数头长度
            httpwebrequest.ContentLength = paramArray.Length;
            //写入登录后的Cookies
            httpwebrequest.Headers.Add("Cookie", _OACookie);
            //请求开始流
            Stream streamrequest = httpwebrequest.GetRequestStream();
            //写入参数
            streamrequest.Write(paramArray, 0, paramArray.Length);
            streamrequest.Close();

            HttpWebResponse response = (HttpWebResponse)httpwebrequest.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
            resultstr = sr.ReadToEnd();
            sr.Close();

            response.Close();
            streamrequest.Close();
            httpwebrequest.Abort();
            return resultstr;
        }

        /// <summary>
        /// 测试
        /// </summary>
        /// <param name="postUrl"></param>
        /// <param name="paramData"></param>
        /// <param name="dataEncode"></param>
        /// <returns></returns>
        public string PostWebRequest(string postUrl, string paramData, Encoding dataEncode, string cookies)
        {
            string ret = string.Empty;
            try
            {
                byte[] byteArray = dataEncode.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";
                webReq.ContentLength = byteArray.Length;
                webReq.Headers.Add("Cookie", cookies);
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();

                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
                ret = ex.Message;
            }
            return ret;
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="msg">消息体</param>
        /// <returns>包装后的消息体</returns>
        public string Log(string msg)
        {
            return msg + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
        /// <summary>
        /// 获取当前人数（测试方法）
        /// </summary>
        /// <param name="_url"></param>
        /// <param name="_cookie"></param>
        /// <returns></returns>
        public string GetPersonNumber(string _url, string _cookie)
        {
            HttpWebRequest httpwebrequest = WebRequest.Create(_url) as HttpWebRequest;
            httpwebrequest.Method = "GET";
            httpwebrequest.Accept = "text/html, application/xhtml+xml, */*";
            httpwebrequest.Referer = "http://oa.hdsxtech.com:8080/general/";
            httpwebrequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0";
            httpwebrequest.ContentType = "text/html; charset=gb2312";
            httpwebrequest.Headers.Add("Cookie", _cookie);
            HttpWebResponse response = (HttpWebResponse)httpwebrequest.GetResponse();
            Stream respStream = response.GetResponseStream();
            StreamReader respReader = new StreamReader(respStream, Encoding.Default);
            string resultHtml = respReader.ReadToEnd();
            respReader.Close();
            response.Close();
            respStream.Close();
            httpwebrequest.Abort();
            return resultHtml;
        }
        /// <summary>
        /// 测试异步请求
        /// </summary>
        /// <param name="_url">传入的请求异步url</param>
        /// <returns>HTML</returns>
        public string TestAsync(string _url)
        {
            //创建一个新的 HttpWebRequest 对象
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
            //设置ContentType属性mime
            request.ContentType = "application/x-www-form-urlencoded";
            //设置请求的方法
            request.Method = "POST";
            //开始异步操作
            request.BeginGetRequestStream(new AsyncCallback(ReadCallback),request);
            //阻止本次线程
            allDone.WaitOne();

            //获取Response
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse);
            string responseString = streamRead.ReadToEnd();

            streamResponse.Close();
            streamRead.Close();

            response.Close();
            return responseString;
        }
        private static void ReadCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            Stream postStream = request.EndGetRequestStream(asynchronousResult);
            string postData = "";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            postStream.Write(byteArray, 0, postData.Length);
            postStream.Close();
            allDone.Set();
        }

        #region 尝试增加异步新方法操作OA
        
        #endregion
    }
}
